// 语言切换功能
class LanguageManager {
    constructor() {
        this.currentLang = this.getCurrentLanguage();
        this.init();
    }

    getCurrentLanguage() {
        // 从存储中获取用户选择的语言，如果没有则使用浏览器默认语言
        return localStorage.getItem('webdavy-language') || 
               (navigator.language.startsWith('zh') ? 'zh_CN' : 'en');
    }

    setLanguage(lang) {
        this.currentLang = lang;
        localStorage.setItem('webdavy-language', lang);
        this.updateUI();
        this.updateToggleButton();
    }

    init() {
        this.setupToggleButton();
        this.updateToggleButton();
        // 延迟执行以确保DOM完全加载
        setTimeout(() => this.updateUI(), 100);
    }

    setupToggleButton() {
        const toggleBtn = document.getElementById('lang-toggle-btn');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => {
                const newLang = this.currentLang === 'zh_CN' ? 'en' : 'zh_CN';
                this.setLanguage(newLang);
            });
        }
    }

    updateToggleButton() {
        const langText = document.getElementById('lang-text');
        const toggleBtn = document.getElementById('lang-toggle-btn');
        
        if (langText) {
            langText.textContent = this.currentLang === 'zh_CN' ? 'EN' : '中';
        }
        
        if (toggleBtn) {
            const tooltip = this.currentLang === 'zh_CN' ? 'Switch to English' : '切换到中文';
            toggleBtn.setAttribute('data-tooltip', tooltip);
        }
    }

    updateUI() {
        // 模拟Chrome i18n API的行为
        this.mockChromeI18n();
        
        // 重新初始化国际化
        if (typeof initializeI18n === 'function') {
            initializeI18n();
        }
    }

    mockChromeI18n() {
        // 创建模拟的chrome.i18n.getMessage函数
        if (!window.chrome) {
            window.chrome = {};
        }
        if (!window.chrome.i18n) {
            window.chrome.i18n = {};
        }

        const messages = this.getMessages();
        
        window.chrome.i18n.getMessage = (key) => {
            return messages[key]?.message || key;
        };
    }

    getMessages() {
        const zhMessages = {
            "appName": {"message": "WebDavy"},
            "appDescription": {"message": "一款快速轻量的 webdav 客户端"},
            "pageTitle": {"message": "WebDavy - 快速轻量的 webdav 客户端"},
            "connectionSettings": {"message": "连接设置"},
            "serverUrl": {"message": "服务器地址"},
            "serverUrlPlaceholder": {"message": "https://example.com/webdav/"},
            "username": {"message": "用户名"},
            "password": {"message": "密码"},
            "autoConnect": {"message": "下次自动连接"},
            "connect": {"message": "连接"},
            "connectTooltip": {"message": "连接到WebDAV服务器"},
            "autoSaveNote": {"message": "配置会自动保存"},
            "logout": {"message": "退出登录"},
            "pathPlaceholder": {"message": "输入路径..."},
            "pathTooltip": {"message": "可编辑路径，按回车键跳转"},
            "parentDir": {"message": "返回上级目录"},
            "refresh": {"message": "刷新当前目录"},
            "listView": {"message": "列表视图"},
            "gridView": {"message": "网格视图"},
            "upload": {"message": "选择文件后立即上传"},
            "newFolder": {"message": "新建文件夹"},
            "connecting": {"message": "正在连接..."},
            "connectSuccess": {"message": "连接成功"},
            "pleaseConnectFirst": {"message": "请先连接到WebDAV服务器"},
            "imageLoadFailed": {"message": "图片加载失败，可能格式不支持"},
            "pleaseSelectFolder": {"message": "请先进入目标文件夹后再上传"},
            "pleaseSelectFiles": {"message": "请选择要上传的文件"},
            "allUploadsFailed": {"message": "所有文件上传均失败"},
            "deleteSuccess": {"message": "删除成功"},
            "folderPathEmpty": {"message": "目录路径不能为空"},
            "creatingFolder": {"message": "正在创建文件夹..."},
            "folderCreated": {"message": "文件夹创建成功"},
            "loggedOut": {"message": "已退出登录"},
            "serverDataError": {"message": "服务器返回数据格式错误"},
            "errorGeneral": {"message": "操作失败，请重试"},
            "errorPathNotFound": {"message": "路径不存在：请检查目录路径是否正确，或先创建父目录"},
            "errorPathFormat": {"message": "路径格式错误：请检查路径是否包含非法字符或格式不正确"},
            "errorResourceConflict": {"message": "资源冲突：目标路径可能已存在，请检查后重试"},
            "errorDeletePermission": {"message": "没有权限删除此资源，根目录通常受保护"},
            "errorPermission": {"message": "没有权限执行此操作，请检查用户权限"},
            "errorAuth": {"message": "认证失败，请检查用户名和密码"},
            "errorNotFound": {"message": "请求的资源不存在"},
            "errorServerInternal": {"message": "服务器内部错误，请稍后重试"}
        };

        const enMessages = {
            "appName": {"message": "WebDavy"},
            "appDescription": {"message": "A fast and lightweight WebDAV client"},
            "pageTitle": {"message": "WebDavy - Fast & Lightweight WebDAV Client"},
            "connectionSettings": {"message": "Connection Settings"},
            "serverUrl": {"message": "Server URL"},
            "serverUrlPlaceholder": {"message": "https://example.com/webdav/"},
            "username": {"message": "Username"},
            "password": {"message": "Password"},
            "autoConnect": {"message": "Auto connect next time"},
            "connect": {"message": "Connect"},
            "connectTooltip": {"message": "Connect to WebDAV server"},
            "autoSaveNote": {"message": "Configuration will be saved automatically"},
            "logout": {"message": "Logout"},
            "pathPlaceholder": {"message": "Enter path..."},
            "pathTooltip": {"message": "Editable path, press Enter to navigate"},
            "parentDir": {"message": "Go to parent directory"},
            "refresh": {"message": "Refresh current directory"},
            "listView": {"message": "List view"},
            "gridView": {"message": "Grid view"},
            "upload": {"message": "Select files and upload immediately"},
            "newFolder": {"message": "New folder"},
            "connecting": {"message": "Connecting..."},
            "connectSuccess": {"message": "Connected successfully"},
            "pleaseConnectFirst": {"message": "Please connect to WebDAV server first"},
            "imageLoadFailed": {"message": "Image loading failed, format may not be supported"},
            "pleaseSelectFolder": {"message": "Please enter target folder before uploading"},
            "pleaseSelectFiles": {"message": "Please select files to upload"},
            "allUploadsFailed": {"message": "All file uploads failed"},
            "deleteSuccess": {"message": "Deleted successfully"},
            "folderPathEmpty": {"message": "Folder path cannot be empty"},
            "creatingFolder": {"message": "Creating folder..."},
            "folderCreated": {"message": "Folder created successfully"},
            "loggedOut": {"message": "Logged out"},
            "serverDataError": {"message": "Server returned invalid data format"},
            "errorGeneral": {"message": "Operation failed, please try again"},
            "errorPathNotFound": {"message": "Path not found: Please check if the directory path is correct, or create the parent directory first"},
            "errorPathFormat": {"message": "Path format error: Please check if the path contains illegal characters or incorrect format"},
            "errorResourceConflict": {"message": "Resource conflict: Target path may already exist, please check and try again"},
            "errorDeletePermission": {"message": "No permission to delete this resource, root directory is usually protected"},
            "errorPermission": {"message": "No permission to perform this operation, please check user permissions"},
            "errorAuth": {"message": "Authentication failed, please check username and password"},
            "errorNotFound": {"message": "The requested resource does not exist"},
            "errorServerInternal": {"message": "Server internal error, please try again later"}
        };

        return this.currentLang === 'zh_CN' ? zhMessages : enMessages;
    }
}

// 初始化语言管理器
let languageManager;

document.addEventListener('DOMContentLoaded', () => {
    languageManager = new LanguageManager();
});